`
The awk command is a super powerful tool, and we encourage you to dig
deeper into its capabilities by running man awk for more information.
Editing Streams with sed
The sed (stream editor) command takes actions on text. For example, it can
replace the text in a file, modify the text in some command’s output, and even
delete selected lines from files.
Let’s use sed to replace any mentions of the word Mozilla with the word
Godzilla in the log.txt file. We use its s (substitution) command and g (global)
command to make the substitution across the whole file, rather than to just the first
occurrence (Listing 2-31).
$ sed 's/Mozilla/Godzilla/g' log.txt
Listing 2-31
Replacing a string with another string
This will output the modified version of the file but won’t change the original
version. You can redirect the output to a new file to save your changes:
$ sed 's/Mozilla/Godzilla/g' log.txt > newlog.txt
We could also use sed to remove any whitespace from the file with the /
// syntax, which will replace whitespace with nothing, removing it from the
output altogether (Listing 2-32).
$ sed 's/ //g' log.txt
Listing 2-32
Removing whitespace with sed
If you need to delete lines of a file, use the d command. In Listing 2-33, 1d
deletes (d) the first line (1).
$ sed '1d' log.txt
Listing 2-33
Deleting the first line with sed
To delete the last line of a file, use the dollar sign ($), which represents the
last line, along with d (Listing 2-34).
$ sed '$d' log.txt
Listing 2-34
Deleting the last line with sed
You can also delete multiple lines, such as line 5 and 7 (Listing 2-35).
$ sed '5,7d' log.txt
Listing 2-35
Deleting lines 5 and 7
Lastly, you can print specific line ranges, such as lines 2 through 15 (Listing
2-36).
$ sed -n '2,15 p' log.txt
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks